package com.surelution.projects.echo.domain

import java.text.SimpleDateFormat;

import com.surelution.projects.domain.User;

import grails.plugins.springsecurity.Secured;

@Secured(["ROLE_ADMIN"])
class BlogController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
	def springSecurityService

	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
    def index = {
		def currDate
		def query = params.month
		println(query);
		if(query && (query.endsWith("<") || query.endsWith(">"))) {
			def diff = query.endsWith("<")?-1:1
			query = query.substring(0, query.length() - 1)
			String[] words = query.split("-")
			int y = Integer.parseInt(words[0])
			int m = Integer.parseInt(words[1])
			m += diff
			Calendar cal = Calendar.getInstance()
			cal.clear()
			cal.set(y, m - 1, 2)
			currDate = cal.time
		} else {
			currDate = new Date()
		}
		Calendar c = Calendar.getInstance()
		c.setTime(currDate)
		int year = c.get(Calendar.YEAR)
		int month = c.get(Calendar.MONTH)
		c.clear()
		c.set(Calendar.YEAR, year)
		c.set(Calendar.MONTH, month)
		c.set(Calendar.DAY_OF_MONTH, 1)
		def firstSightOfThisMonth = c.time
		
		c.add(Calendar.MONTH, 1)
		def firstSightOfNextMonth = c.time
		
		
		def comments = Comment.findAllByCreateTimeBetween(firstSightOfThisMonth, firstSightOfNextMonth)
		comments = comments.findAll {comment->
			comment.blog.type.equals("OPEN")
		}
		[comments : comments, currentDate : currDate]
    }
	
	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
	def openComments = {
		params.max = Math.min(params.max ? params.int('max') : 5, 100)
		params.offset = params.offset?:0
		def blogs = Blog.findAll("from Blog b where b.type=:type order by b.createTime desc",[type:Status.OPEN],params)
		def blogInstanceTotal = Blog.executeQuery("select count(b) from Blog b where b.type=:type",[type:Status.OPEN])[0]
		def newBlogs = Blog.findAll("from Blog b where b.type=:type order by b.createTime desc",[type:Status.NEW],params)
		def newBlogTotal = Blog.executeQuery("select count(b) from Blog b where b.type=:type",[type:Status.NEW])[0]
		def readBlogs = Blog.findAll("from Blog b where b.type=:type order by b.createTime desc",[type:Status.READ],params)
		def readBlogTotal = Blog.executeQuery("select count(b) from Blog b where b.type=:type",[type:Status.READ])[0]
		[blogInstanceList:blogs, blogInstanceTotal:blogInstanceTotal,newBlogList:newBlogs, newBlogTotal:newBlogTotal,readBlogsList:readBlogs, readBlogTotal:readBlogTotal]
	}

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 5, 100)
		def from = params.dateFrom
		def to = params.dateTo
		def type = params.type
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
		def dateFrom, dateTo
		if(!from) {
			from = new Date(0)
		}
		if(!to) {
			to = new Date()
		}
		
        [blogInstanceList: Blog.findAllByCreateTimeBetweenAndType(from, to, type), 
			blogInstanceTotal: Blog.countByCreateTimeBetweenAndType(from, to, type)]
    }

	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
    def create = {
        def blogInstance = new Blog()
		if (!params.title){
			blogInstance.properties = params
			return [blogInstance: blogInstance]
		}
		else{
			render(view: "create")
			}
    }

	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
    def save = {
        def blogInstance = new Blog(params)
		blogInstance.type = Blog.TYPE_NEW
		blogInstance.createTime = new Date()
        if (blogInstance.save(flush: true)&&(params.title!="")) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
            redirect(action: "openComments")
        }
        else {
			blogInstance.delete(flush: true)
			flash.message = "${message(code: 'default.created.message.error', default:"null")}"
            redirect(action: "openComments")
        }
    }

	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
    def show = {
        def blogInstance = Blog.get(params.id)
        if (!blogInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
            redirect(action: "list")
        }
        else {
			def comments = Comment.findAllByBlog(blogInstance)
            [blogInstance: blogInstance, comments :comments]
        }
    }

    def edit = {
        def blogInstance = Blog.get(params.id)
        if (!blogInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
            redirect(action: "list")
        }
        else {
            return [blogInstance: blogInstance]
        }
    }

    def update = {
        def blogInstance = Blog.get(params.id)
        if (blogInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (blogInstance.version > version) {
                    
                    blogInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'blog.label', default: 'Blog')] as Object[], "Another user has updated this Blog while you were editing")
                    render(view: "edit", model: [blogInstance: blogInstance])
                    return
                }
            }
            blogInstance.properties = params
            if (!blogInstance.hasErrors() && blogInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
                redirect(action: "show", id: blogInstance.id)
            }
            else {
                render(view: "edit", model: [blogInstance: blogInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def blogInstance = Blog.get(params.id)
        if (blogInstance) {
            try {
                blogInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
                redirect(action: "openComments")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'blog.label', default: 'Blog'), blogInstance.title])}"
            redirect(action: "openComments")
        }
    }
	
	def comment = {
		def blog = Blog.get(params.id)
		if(blog&&(params.title!="")) {
			def comment = new Comment()
			comment.blog = blog
			return [commentInstance : comment, blogInstance:blog]
		}
		redirect(action : "list")
	}
	
	def saveComment = {
		def commentInstance = new Comment(params)
		commentInstance.createTime = new Date()
		def user = User.get(springSecurityService.principal.id)
		commentInstance.user = user
		if (commentInstance.save(flush: true)) {
			flash.message = "${message(code: 'default.created.message', args: [message(code: 'comment.label', default: 'Comment'), commentInstance.title])}"
			redirect(action: "show", id: commentInstance.blog.id)
		}
	}
	
	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
	def commentWithId = {
		def comment = Comment.get(params.id)
		if(comment) {
			def blog = comment.blog
			if(blog) {
				redirect(action: "show", id: blog.id)
			}
		}
	}
	
	def updateStatus = {
		def blog = Blog.get(params.id)
		if(blog && params.type) {
			blog.type = params.type
			blog.save(flush : true)
		}
		redirect(action: "show", id: blog.id)
	}
	
	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
	def blogContent = {
		def blog = Blog.get(params.id)
		[blog:blog]
	}
	
	@Secured(["IS_AUTHENTICATED_ANONYMOUSLY"])
	def commentContent = {
		def comment = Comment.get(params.id)
		[comment:comment]
	}
}
